from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from app.exchange import check_code, exchange_proxy

def txsp_invoke(country_code, phone_num, phone_code_url, exchange_code):
    proxy_info = exchange_proxy.proxy_method();
    options = webdriver.FirefoxOptions()
    options.add_argument(f'--proxy-server=http://{proxy_info[0]}:{proxy_info[1]}')

    driver = webdriver.Firefox(options=options)
    driver.get("https://film.qq.com/duihuan.html")
    driver.maximize_window()

    # 登陆QQ或微信
    time.sleep(2)
    agree_tag = WebDriverWait(driver, 5).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'policy-module_select-box__-61C9')))
    agree_tag.click()

    # 登陆QQ
    # time.sleep(1)
    # qq_button = driver.find_element(By.CLASS_NAME, 'login-button-module_qq-button-container__c7odm')
    # qq_button.click()

    # 登陆微信
    time.sleep(1)
    wx_tag = driver.find_element(By.CLASS_NAME, 'login-button-module_wx-buttton-container__FE7En')
    wx_tag.click()

    # 等待用户扫码完成
    input('请在浏览器中完成操作后，按 Enter 键继续...')

    # 输入兑换码
    time.sleep(2)
    redeem_input = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.ID, 'cdkey')))
    redeem_input.send_keys(exchange_code)

    # 点击获取验证码
    time.sleep(2)
    sms_send = driver.find_element(By.ID, 'sms_code_btn')
    sms_send.click()

    # 调用获取验证码接口填写验证码
    time.sleep(5)
    code = check_code.get_check_code(phone_code_url)
    verify_code = driver.find_element(By.ID, 'vcode')
    verify_code.send_keys(code)

    # 点击兑换
    exchange_button = driver.find_element(By.ID, 'cdkey_btn')
    exchange_button.click()

    # 退出
    time.sleep(5)
    driver.quit()

if __name__ == '__main__':
    txsp_invoke(1, 1, 1, 'xxxx-1234-txsp-month1')